from .base import PermissionHandler
from stark.service.v1 import StarkConfig, StarkModelForm
from stark.service.v1 import get_choice_text, get_datetime_text

from django import forms


class MeterReadingConfig(PermissionHandler, StarkConfig):
    
    def get_model_form_class(self, is_add, request, pk, *args, **kwargs):
        # 定义模型表单类，动态排除指定字段
        class ModelForm(StarkModelForm):
            reading_date = forms.DateField(
                widget=forms.DateInput(
                    attrs={'type': 'date'},  # 使用HTML5日期选择器
                    format='%Y-%m-%d'  # 日期格式
                ),
                input_formats=['%Y-%m-%d'],  # 接受的输入格式
                label="抄表日期"
            )
            
            class Meta:
                model = self.model_class  # 关联到当前模型
                # 方法1：明确指定需要显示的字段（推荐，更安全）
                # fields = ["house", "meter_type", "reading_date", "current_reading"]
            
                # 方法2：排除不需要的字段
                exclude = ["previous_reading", "consumption"]
    
        return ModelForm

    list_display = ["house", get_choice_text("表类型", "meter_type"), get_datetime_text("抄表日期", "reading_date"), "previous_reading", "current_reading", "consumption"]
    #
    # def add_view(self, request, *args, **kwargs):
    #     """
    #     添加页面，在GET请求时预填上期数据
    #     :param request:
    #     :return:
    #     """
    #     model_form_class = self.get_model_form_class(True, request, None, *args, **kwargs)
    #
    #     if request.method == 'GET':
    #         # 获取请求参数中的房源和表类型（如果有）
    #         house_id = request.GET.get('house')
    #         meter_type = request.GET.get('meter_type')
    #
    #         # 初始化表单数据字典
    #         initial_data = {}
    #
    #         # 如果有房源和表类型参数，查询上期数据
    #         if house_id and meter_type:
    #             try:
    #                 # 查询同一房源、同一类型的最新记录
    #                 last_record = self.model_form_class.objects.filter(
    #                     house_id=house_id,
    #                     meter_type=meter_type
    #                 ).order_by('-reading_date').first()
    #
    #                 # 如果有上期记录，预填读数设为上期的本次读数
    #                 if last_record:
    #                     initial_data['previous_reading'] = last_record.current_reading
    #             except Exception as e:
    #                 # 处理可能的查询错误
    #                 pass
    #
    #         # 使用初始数据创建表单
    #         form = model_form_class(initial=initial_data)
    #         form.is_image_form = self.has_image_field and self.image_field_name
    #         return render(request, self.add_template or 'stark/change.html', {'form': form})
    #
    #     # POST请求处理逻辑（保持不变）
    #     form = model_form_class(data=request.POST, files=request.FILES)
    #     form.is_image_form = self.has_image_field and self.image_field_name
    #
    #     if form.is_valid():
    #         instance = form.save(commit=False)
    #         instance.save()
    #         form.save_m2m()
    #         messages.add_message(request, messages.SUCCESS, "添加成功！")
    #         return redirect(self.reverse_list_url(*args, **kwargs))
    #
    #     messages.add_message(request, settings.MESSAGE_DANGER_TAG, "添加失败！")
    #     return render(request, self.add_template or 'stark/change.html', {'form': form})
